<?php
includePackage('Video');
class RSSDataParser extends SimpleXMLDataParser {

    protected $itemClass  ='VideoObject';
    protected $useDescriptionForContent = false;
    static $standardProperties = array('title', 'link', 'description','content','pubdate','category','author');
    public function parseData($data) {
        $items = array();
        if (!$feed = parent::parseData($data, true)) {
            return $items;
        }
        if (isset($feed['channel'])) {
            $items = $this->parseChannel($feed['channel']);
        } else {
            throw new KurogoException("Don't know how to parse this feed yet");
        }

        if (is_null($this->totalItems)) {
            $this->setTotalItems(count($items));
        }

        return $items;
    }

    protected function parseChannel($channel) {
        $channelItems = Kurogo::arrayVal($channel, 'item', array());
        $items = array();
        foreach ($channelItems as $itemData) {
            if ($item = $this->parseItem($itemData)) {
                $items[] = $item;
            }
        }
        
        return $items;
    }

    protected function parseItem($itemData) {
        $item = new VideoObject();
        $item->setTitle($itemData['title']);
        $item->setUrl($itemData['link']);
        $arr = explode("id/", $itemData['link']);
        $item->setId($arr[1]);
        $arr1 = explode("src='", $itemData['description']);
        $arr2 = explode("' ", $arr1[1]);
        $item->setImage($arr2[0]);
        $item->setStillFrameImage($arr2[0]);
        $date = new DateTime($itemData['pubdate']);
        $item->setPublished($date);

        return $item;
    }

    public function setItemClass($itemClass)
    {
    	if ($itemClass) {
    		if (!class_exists($itemClass)) {
    			throw new KurogoConfigurationException("Cannot load class $itemClass");
    		}
			$this->itemClass = $itemClass;
		}
    }

    protected function getPropertyForKey($key)
    {
        if (in_array($key, self::$standardProperties)) {
            return $key;
        }
        
        $propertyMap = array_merge(array(
            'content:encoded'=>'content',
            'guid'=>'id',
            'dc:creator'=>'author',
            'dc:date'=>'pubdate',
            'dc:subject'=>'category',
            'enclosure'=>'thumbnail',
            'media:content'=>'thumbnail',
            'media:thumbnail'=>'thumbnail',
            'media:group'=>'mediagroup',
            'body'=>'content',
        ), $this->userFields);
                        
        return Kurogo::arrayVal($propertyMap, $key);
    }
}
